package ch.kerbtier.webglue;

import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class GlueContextListener implements ServletContextListener{
	
	private Logger logger = Logger.getLogger(GlueContextListener.class.getName());
	
	public void contextDestroyed(ServletContextEvent sce) {
		final CodeRunner codeRunner = (CodeRunner)sce.getServletContext().getAttribute("glue_code_runner");
		Map<String, Object> parameters = new HashMap<String, Object>();
        parameters.put("servletContext", sce.getServletContext());
        parameters.put("context", sce.getServletContext());
        
        codeRunner.run("contextDestroyed.groovy", parameters);
	}

	public void contextInitialized(ServletContextEvent sce) {
		
		String type = sce.getServletContext().getInitParameter("glue-runner");
		
	    String[] roots = new String[] {sce.getServletContext().getRealPath("WEB-INF/glue")};
	    
	    CodeRunner codeRunner = null;
	    if("groovyClassloader".equals(type)){
	    	codeRunner = new GroovyNonReloadable(roots[0]);
	    	logger.info("using 'GroovyNonReloadable' webglue coderunner");

	    }else{	// default is GroovyReloadable
	    	codeRunner = new GroovyReloadable(roots);
	    	logger.info("using 'GroovyReloadable' webglue coderunner");
	    }
	    
		sce.getServletContext().setAttribute("glue_code_runner", codeRunner);
		
		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("servletContext", sce.getServletContext());
        parameters.put("context", sce.getServletContext());
        
		codeRunner.run("contextCreated.groovy", parameters);
	}
}
